﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLayer.Model.Services.Abstract;
using BusinessLayer.Model.Services.Concrete;
using BusinessLayer.Model.Repositories.Abstract;

using BusinessLayer.Model.Entities;
using System.Web.Security;
using BusinessLayer;
using DataAccess.Repositories;

namespace intecnologia.Admin
{
    public partial class AdminDetails : System.Web.UI.Page
    {
        ISessionService _sessionService = new SessionService();
        IAccountRepository _accountRepository = new AccountRepository();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (_sessionService.SessionExpired())
                Response.Redirect("~/Admin/Default.aspx");
        }

        protected void btnChangePassword_Click(object sender, EventArgs e)
        {
            ChangeAdminPassword();
        }

        protected void btnExit_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/Default.aspx");
        }

        private void ChangeAdminPassword()
        {
            Account admin = _accountRepository.FetchByUsername("admin");

            string oldPass = FormsAuthentication.HashPasswordForStoringInConfigFile(tbOldPassword.Text.Trim(), Constants.EncryptionMethod);// Encryption.Encrypt(tbOldPassword.Text.Trim(), Constants.EncryptionClearText);
            string newPass = FormsAuthentication.HashPasswordForStoringInConfigFile(tbNewPassword.Text.Trim(), Constants.EncryptionMethod);//Encryption.Encrypt(tbNewPassword.Text.Trim(), Constants.EncryptionClearText);
            string newPassConfirm = FormsAuthentication.HashPasswordForStoringInConfigFile(tbConfirmPassword.Text.Trim(), Constants.EncryptionMethod);//Encryption.Encrypt(tbConfirmPassword.Text.Trim(), Constants.EncryptionClearText);

            if (oldPass != admin.Password)
            {
                lblChangePassError.Text = "La clave antigua es incorrecta.";
                lblChangePassError.Visible = true;
            }

            else if (newPass != newPassConfirm)
            {
                lblChangePassError.Text = "La clave nueva no concuerda con la de confirmación.";
                lblChangePassError.Visible = true;
            }

            else
            {
                _accountRepository.ChangePassword(admin, newPass);

                lblChangePassError.Text = "La clave fue cambiada satisfactoriamente.";
                lblChangePassError.Visible = true;
            }
        }

    }
}
